package com.woniuxy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.dto.*;
import com.woniuxy.entity.ShopTable;
import com.woniuxy.entity.WarehouseShop;
import com.woniuxy.entity.WarehouseTable;
import com.woniuxy.enums.CodeEnum;
import com.woniuxy.exception.PawnShopException;
import com.woniuxy.mapper.ShopTableMapper;
import com.woniuxy.param.ListShopParam;
import com.woniuxy.param.SaveShopParam;
import com.woniuxy.param.UpdateShopParam;
import com.woniuxy.service.ShopTableService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.WarehouseShopService;
import com.woniuxy.service.WarehouseTableService;
import com.woniuxy.util.WoniuBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zcx, ftl, gr, rhs
 * @since 2021-12-31
 */
@Service
public class ShopTableServiceImpl extends ServiceImpl<ShopTableMapper, ShopTable> implements ShopTableService {
    @Autowired
    private WarehouseShopService warehouseShopService;
    @Autowired
    private WarehouseTableService warehouseTableService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public SaveShopDto saveShop(SaveShopParam saveShopParam) {
        ShopTable one = getOne(new QueryWrapper<ShopTable>().eq("shop_name", saveShopParam.getShopName()));
        if (null != one) {
            throw new PawnShopException(CodeEnum.SHOP_FALL.getMessage(), CodeEnum.SHOP_FALL.getCode());
        }
        ShopTable shopTable = WoniuBeanUtils.copyObject(saveShopParam, ShopTable.class);
        boolean save = save(shopTable);
        if (save) {
            SaveShopDto saveShopDto = WoniuBeanUtils.copyObject(shopTable, SaveShopDto.class);
            ArrayList<WarehouseShop> warehouseShops = new ArrayList<>();
            for (Integer warehouseId : saveShopParam.getWarehouseIds()) {
                WarehouseTable table = warehouseTableService.getById(warehouseId);
                WarehouseShop shop = new WarehouseShop();
                shop.setShopId(saveShopDto.getShopId());
                shop.setShopName(saveShopDto.getShopName());
                shop.setWarehouseId(warehouseId);
                shop.setWarehouseName(table.getWarehouseName());
                warehouseShops.add(shop);
            }
            boolean b = warehouseShopService.saveBatch(warehouseShops);
            if (b) {
                return saveShopDto;
            } else {
                throw new PawnShopException(CodeEnum.PAWN_SHOW_SAVE_FAIL.getMessage(), CodeEnum.PAWN_SHOW_SAVE_FAIL.getCode());
            }
        }
        throw new PawnShopException(CodeEnum.PAWN_SHOW_SAVE_FAIL_1.getMessage(), CodeEnum.PAWN_SHOW_SAVE_FAIL_1.getCode());
    }

    @Override
    public PageShopDto listShop(ListShopParam listShopParam) {
        QueryWrapper<ShopTable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_remove_status", 0);

        if (null != listShopParam.getKeyword()) {
            queryWrapper.and(qw -> {
                qw.like("shop_name", listShopParam.getKeyword()).or()
                        .like("shop_linkman", listShopParam.getKeyword()).or()
                        .like("shop_phone", listShopParam.getKeyword());
            });
        }
        if (!StringUtils.isEmpty(listShopParam.getShopStatus())) {
            queryWrapper.eq("shop_status", listShopParam.getShopStatus());
        }

        IPage<ShopTable> iPage = page(new Page<>(listShopParam.getIndexPage(), listShopParam.getPageSize()), queryWrapper);
        PageShopDto pageShopDto = new PageShopDto();
        pageShopDto.setIndexPage(iPage.getCurrent());
        pageShopDto.setTotal(iPage.getTotal());
        pageShopDto.setShopDtoList(WoniuBeanUtils.copyList(iPage.getRecords(), ShopDto.class));

        for (ShopDto shopDto : pageShopDto.getShopDtoList()) {
            String s = "";
            List<WarehouseShopDto> warehouseShopDtos = warehouseShopService.listWareHouseByShopId(shopDto.getShopId());
            for (int i = 0; i < warehouseShopDtos.size(); i++) {
                s += "," + warehouseShopDtos.get(i).getWarehouseName();
            }

            s = s.replaceFirst(",", " ");

            shopDto.setWarehouseName(s);
        }
        return pageShopDto;
    }

    @Override
    public Boolean updateShop(UpdateShopParam updateShopParam) {
        ShopTable shopTable = new ShopTable();
        shopTable.setShopId(updateShopParam.getShopId());
        shopTable.setShopName(updateShopParam.getShopName());
        shopTable.setShopLinkman(updateShopParam.getShopLinkman());
        shopTable.setShopPhone(updateShopParam.getShopPhone());
        shopTable.setShopStatus(updateShopParam.getShopStatus());
        shopTable.setShopAddress(updateShopParam.getShopAddress());
        boolean b = updateById(shopTable);

        //通过传入的店铺id删除仓库店铺中间表的数据，清除关联从新添加关联
        warehouseShopService.remove(new QueryWrapper<WarehouseShop>().eq("shop_id", updateShopParam.getShopId()));
        //根据前端传入仓库id集合查询仓库信息
        List<WarehouseTable> warehouseTables = warehouseTableService.listByIds(updateShopParam.getWarehouseIds());
        //创建一个仓库商店对象集合
        List<WarehouseShop> WarehouseShops = new ArrayList<>();
        //遍历仓库对象，获取仓库id、仓库名设置到仓库商店对象中
        for (WarehouseTable warehouseTable : warehouseTables) {
            WarehouseShop warehouseShop = new WarehouseShop();
            warehouseShop.setShopId(updateShopParam.getShopId());
            warehouseShop.setShopName(updateShopParam.getShopName());
            warehouseShop.setWarehouseId(warehouseTable.getWarehouseId());
            warehouseShop.setWarehouseName(warehouseTable.getWarehouseName());
            WarehouseShops.add(warehouseShop);
        }
        //数据存入仓库商店中间表中
        boolean b1 = warehouseShopService.saveBatch(WarehouseShops);
        if (!b1)
            throw new PawnShopException(CodeEnum.PAWN_SAVE_FAIL.getMessage(), CodeEnum.PAWN_SAVE_FAIL.getCode());
        return b;
    }

    @Override
    public Boolean delShop(List<Integer> shopIds) {
        List<ShopTable> shopTableList = list(new QueryWrapper<ShopTable>().in("shop_id", shopIds));
        if (null == shopTableList || shopTableList.size() <= 0)
            throw new PawnShopException(CodeEnum.PAWN_DELETE_FAIL_1.getMessage(), CodeEnum.PAWN_DELETE_FAIL_1.getCode());
        List<ShopTable> collect = shopTableList.stream().filter(general -> {
            Boolean flag = !(general.getShopRemoveStatus() == 1);
            if (flag) general.setShopRemoveStatus(1);
            return flag;
        }).collect(Collectors.toList());
        if (collect.size() != shopTableList.size())
            throw new PawnShopException(CodeEnum.PAWN_DELETE_FAIL_2.getMessage(), CodeEnum.PAWN_DELETE_FAIL_2.getCode());

        return updateBatchById(collect);
    }




    @Override
    public GetShopDto getShopById(Integer shopId) {
        List<WarehouseShopDto> warehouseShopDtos = warehouseShopService.listWareHouseByShopId(shopId);
        List<WarehouseShop> warehouseShops = WoniuBeanUtils.copyList(warehouseShopDtos, WarehouseShop.class);
        //存放此店铺下属仓库的id集合

        List<Integer> warehouseIds = new ArrayList<>();
        //存放此店铺下属仓库的name集合
        List<Integer> warehouseShopIds = new ArrayList<>();
        for (WarehouseShop warehouseShop : warehouseShops) {
            warehouseIds.add(warehouseShop.getWarehouseId());
            warehouseShopIds.add(warehouseShop.getWarehouseShopId());
        }
        GetShopDto getShopDto = new GetShopDto();
        ShopTable shopTable = getById(shopId);
        GetShopDto getShopDto1 = WoniuBeanUtils.copyObject(shopTable, GetShopDto.class);
        getShopDto = getShopDto1;
        getShopDto.setWarehouseIds(warehouseIds);

        getShopDto.setWarehouseShopIds(warehouseShopIds);
        return getShopDto;
    }

    @Override
    public List<ShopDto> listShops() {
        List<ShopTable> list = list(new QueryWrapper<ShopTable>().eq("shop_remove_status", 0).eq("shop_status", 0));
        return WoniuBeanUtils.copyList(list, ShopDto.class);
    }


}
